from flask import request
from sqlalchemy import or_

from common.libs.Restful import Restful
from common.libs.UrlManager import UrlManager
from common.models.foods.Food import Food
from common.models.foods.FoodCate import FoodCat
from web.controllers.api import api_route


@api_route.route('/food/index/', methods=['POST'])
def foodIndex():
    cate_lists = FoodCat.query.filter_by(status=1).order_by(FoodCat.weight.desc()).all()
    data_cat_list = []
    data_cat_list.append({
        'id': 0,
        'name': '全部'
    })
    if cate_lists:
        for item in cate_lists:
            tmp_data = {
                'id': item.id,
                'name': item.name
            }
            data_cat_list.append(tmp_data)
    food_list = Food.query.filter_by(status=1).order_by(Food.total_count.desc(), Food.id.desc()).limit(3).all()
    data_food_list = []
    if food_list:
        for item in food_list:
            tmp_data = {
                'id': item.id,
                'pic_url': UrlManager.buildImageUrl(item.main_image)
            }
            data_food_list.append(tmp_data)
    result = {
        'cate_list': data_cat_list,
        'food_list': data_food_list
    }
    return Restful.success(data=result)


@api_route.route('/food/list/', methods=['POST'])
def foodList():
    cate_id = request.form.get('cate_id', 0)
    mix_kw = request.form.get('mix_kw', '')
    p = int(request.form.get('p', 1))
    if p < 1:
        p = 1
    page_size = 10
    offset = (p-1)*page_size

    query = Food.query.filter_by(status=1)
    if cate_id != '0' and cate_id:
        query = query.filter_by(cat_id=cate_id)
    if mix_kw:
        query.filter(or_(Food.name.like('%'+mix_kw+'%'), Food.tags.like('%'+mix_kw+'%')))
    food_list = query.order_by(Food.total_count.desc(), Food.id.desc()).offset(offset).limit(page_size).all()
    data_food_list = []
    for item in food_list:
        food_dic = {
            'id': item.id,
            'name': item.name,
            'price': str(item.price),
            'pic_url': UrlManager.buildImageUrl(item.main_image),
            'tags': item.tags,
            'min_price': str(item.price),
            'update_time': item.updated_time
        }
        data_food_list.append(food_dic)
    # 判断是否还有数据
    has_more = 0 if len(data_food_list) < page_size else 1
    return Restful.success(data={'food_list': data_food_list, 'has_more': has_more})


@api_route.route('/food/info/', methods=['POST'])
def foodInfo():
    req = request.values
    id = int(req['id']) if 'id' in req else 0
    food_info = Food.query.filter_by(id=id).first()
    if not food_info:
        return Restful.notfound_error('商品已下架！')
    resp = {
        'info': {
            'id': food_info.id,
            'name': food_info.name,
            'summary': food_info.summary,
            'total_count': food_info.total_count,
            'comment_count': food_info.comment_count,
            'main_image': UrlManager.buildImageUrl(food_info.main_image),
            'price': str(food_info.price),
            'stock': food_info.stock,
            'pics': [UrlManager.buildImageUrl(food_info.main_image)]
        }
    }
    return Restful.success(data=resp)
